import { randomUUID } from 'node:crypto'
import { sql, relations } from 'drizzle-orm'
import { sqliteTable, text, integer, index, uniqueIndex } from 'drizzle-orm/sqlite-core'

export const users = sqliteTable('users', {
  id: text()
    .primaryKey()
    .$defaultFn(() => randomUUID()),
  email: text().notNull().unique(),
  nickname: text().notNull(),
  passwordHash: text().notNull(),
  avatar: text(),
  emailVerified: integer({ mode: 'boolean' }).notNull().default(false),
  createdAt: integer({ mode: 'timestamp' })
    .notNull()
    .default(new Date()),
}, (table)=>({
  emailIdx: uniqueIndex('email_idx').on(table.email),
}))

// 验证码表 (用于注册验证/登录/密码重置)
export const verificationCodes = sqliteTable('verification_codes', {
  id: text()
    .primaryKey()
    .$defaultFn(() => randomUUID()),
  email: text('email').notNull(),
  code: text('code').notNull(), // 6位验证码或二维码token
  type: text('type').notNull(), // 'register' | 'login' | 'reset'
  expiresAt: integer({ mode: 'timestamp' }).notNull(),
  used: integer({ mode: 'boolean' }).default(false),
});


export const usersRelations = relations(users, ({ many }) => ({
  chats: many(chats),
  // emailVerificationTokens: many(emailVerificationTokens),
}))

export const chats = sqliteTable(
  'chats',
  {
    id: text()
      .primaryKey()
      .$defaultFn(() => randomUUID()),
    title: text(),
    userId: text().notNull(),
    createdAt: integer({ mode: 'timestamp' })
      .notNull()
      .default(sql`(unixepoch())`),
  },
  t => [index('userIdIdx').on(t.userId)]
)

export const chatsRelations = relations(chats, ({ one, many }) => ({
  user: one(users, {
    fields: [chats.userId],
    references: [users.id],
  }),
  messages: many(messages),
}))

export const messages = sqliteTable(
  'messages',
  {
    id: text()
      .primaryKey()
      .$defaultFn(() => randomUUID()),
    chatId: text()
      .notNull()
      .references(() => chats.id, { onDelete: 'cascade' }),
    role: text({ enum: ['user', 'assistant'] }).notNull(),
    parts: text().notNull(),
    createdAt: integer({ mode: 'timestamp' })
      .notNull()
      .default(sql`(unixepoch())`),
  },
  t => [index('chatIdIdx').on(t.chatId)]
)

export const messagesRelations = relations(messages, ({ one }) => ({
  chat: one(chats, {
  fields: [messages.chatId],
  references: [chats.id],
}),
}))

